package edu.lsnu.equipment_management_system.controller;

import edu.lsnu.equipment_management_system.pojo.vo.out.session.UserVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

/**
 * @author mzywucai
 * @Description 生成头像的图片[取姓名的姓]
 * @date 2018/12/10
 */
@RestController
public class GenerateAvatarController {

    @GetMapping("/api/getAvatar")
    public void getAvatar(HttpServletRequest request, HttpServletResponse response) {
        BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D g = (Graphics2D) img.getGraphics();
        g.setBackground(Color.WHITE);
        // 绘制头像图片
        g.setFont(new Font("华文行楷", Font.BOLD, 72));

        Color color = randomColor();

        g.setColor(color);

        HttpSession session = request.getSession();
        UserVo user = (UserVo) session.getAttribute("user");
        UserVo admin = (UserVo) session.getAttribute("admin");
        if (null != user) {
            g.drawString(user.getUserName().substring(0, 1), 10, 68);
        } else if (null != admin) {
            g.drawString(admin.getUserName().substring(0, 1), 10, 68);
        } else {
            // 永远都执行不到的！
            g.drawString("彩", 12, 65);
        }


        g.dispose();

        // 输出图片
        response.setContentType("image/png");
        try {
            ImageIO.write(img, "png", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /** 获取指定长度的16进制字符串. */
    public static String randomHexStr(int len) {
        ArrayList<String> colorArr = new ArrayList<String>();
        // -------------------
        colorArr.add("8A2BE2");
        colorArr.add("4169E1");
        colorArr.add("008B8B");
        colorArr.add("2E8B57");
        colorArr.add("808000");
        colorArr.add("DAA520");
        colorArr.add("228B22");
        colorArr.add("3CB371");
        colorArr.add("00BFFF");
        colorArr.add("A52A2A");
        // -------------------

        Random random = new Random(System.currentTimeMillis());
        int i = random.nextInt(10);

        return colorArr.get(i);
    }

    public static Color randomColor() {
        int color = Integer.valueOf(randomHexStr(6), 16);
        return new Color(color);
    }
}
